<!--
 * @Author       : wfl
 * @LastEditors: ww
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-23 15:50:42
 * @LastEditTime: 2023-06-30 16:07:02
-->
<script lang="ts" setup name="ApprovalNode">
import Node from '@main/views/approve-workflow/WorkFlow/tree-node/Node.vue'
import { computed, reactive } from 'vue'
import { EApproveCategory, EApproveType } from '@main/views/approve-workflow/enum'

const props = defineProps({
  config: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const emits = defineEmits<{
  (e: 'selected'): void
  (e: 'insertNode', val: string): void
  (e: 'delNode', node: any): void
}>()

const flowStore = useFlowStore()

const state = reactive({
  showError: false,
  errorInfo: ''
})

const content = computed(() => {
  const config = props.config.props
  if (config.approveType === EApproveType.自动通过)
    return '自动通过'

  else if (config.approveType === EApproveType.自动拒绝)
    return '自动拒绝'

  switch (config?.approvalCategory) {
    case EApproveCategory.指定成员:
      if (config.assignedUser.length > 0 || [EApproveType.自动拒绝, EApproveType.自动通过].includes(config.approveType)) {
        const texts: any[] = []
        if ([EApproveType.自动拒绝, EApproveType.自动通过].includes(config.approveType)) {
          texts.push(`${config.approveType === EApproveType.自动拒绝 ? '自动拒绝' : '自动通过'}`)
        }
        else {
          config.assignedUser.forEach((org: { elementName: string; }) =>
            texts.push(org.elementName)
          )
        }
        return String(texts).replaceAll(',', '、')
      }
      else {
        return '请指定审批人'
      }
    case EApproveCategory.发起人自己:
      return '发起人自己'
    case EApproveCategory.发起人自选:
      return config.selfSelect.multiple ? '发起人自选多人' : '发起人自选一人'
    // case EApproveCategory.多级主管依次审批:
    //   return "多级主管依次审批";
    case EApproveCategory.发起人部门主管:
      return config.leader.level > 1
        ? `发起人的第 ${config.leader.level} 级主管`
        : '发起人的直接主管'
    case EApproveCategory.联系人控件关联成员:
      if (!config.formUser || config.formUser === '') {
        return '表单内联系人控件（未选择）'
      }
      else {
        const opt = getFormItemById(config.formUser)
        if (opt?.text || opt?.options?.label || opt?.widgetName)
          return `联系人控件（${opt?.text || opt?.options?.label || opt?.widgetName}）关联成员`
        else
          return '该表单已被移除!'
      }
    case EApproveCategory.部门控件关联角色:
      if (!config.formDep || config.formDep === '') {
        return '表单部门控件（未选择）'
      }
      else {
        const opt = getFormItemById(config.formDep)
        if (opt?.text || opt?.options?.label || opt?.widgetName)
          return `部门控件（${opt?.text || opt?.options?.label || opt?.widgetName}）关联角色`
        else
          return '该表单已被移除!'
      }
    case EApproveCategory.组织控件关联角色:
      if (!config.formOrg || config.formOrg === '') {
        return '表单组织控件（未选择）'
      }
      else {
        const opt = getFormItemById(config.formOrg)
        if (opt?.text || opt?.options?.label || opt?.widgetName)
          return `组织控件（${opt?.text || opt?.options?.label || opt?.widgetName}）关联角色`
        else
          return '该表单已被移除!'
      }
    case EApproveCategory.指定角色:
      if (config.assignedUser.length > 0) {
        return String(config.assignedUser.map((c: any) => c.elementName)).replaceAll(
          ',',
          '、'
        )
      }
      else {
        return '指定角色（未设置）'
      }
    default:
      return '未知设置项'
  }
})

const getFormItemById = (id: string) => {
  return (
    flowStore.design?.formItems?.find(
      (item: { id?: string; widgetName?: string; }) => item.id === id || item.widgetName === id
    ) || null
  )
}
// 校验数据配置的合法性
const validate = (err: string[]) => {
  try {
    return (state.showError
      = !validated[`${props.config.props.approvalCategory as keyof typeof validated}`](err))
  }
  catch (e) {
    return true
  }
}

const validated = {
  SPECIFIED_USER: (err: string[]) => {
    if (props.config.props.assignedUser.length > 0 || [EApproveType.自动拒绝, EApproveType.自动通过].includes(props.config.props.approveType)) {
      return true
    }
    else {
      state.errorInfo = '请指定审批人员'
      err.push(`${props.config.name} 未指定审批人员`)
      return false
    }
  },
  INITIATOR_SPECIFIED: () => {
    return true
  },
  INITIATOR_DEPT_MANAGER: () => {
    return true
  },
  LEADER: () => {
    return true
  },
  ROLE: (err: string[]) => {
    if (props.config.props.assignedUser.length <= 0) {
      state.errorInfo = '请指定负责审批的系统角色'
      err.push(`${props.config.name} 未指定审批角色`)
      return false
    }
    return true
  },
  INITIATOR_SELF: () => {
    return true
  },
  USER_SELECT_COMPONENT: (err: string[]) => {
    if (props.config.props.formUser === '') {
      state.errorInfo = '请指定表单中的人员组件'
      err.push(`${props.config.name} 审批人为表单中人员，但未指定`)
      return false
    }
    return true
  },
  DEPT_SELECT_COMPONENT: (err: string[]) => {
    if (props.config.props.formDep === '') {
      state.errorInfo = '请指定表单中的部门控件'
      err.push(`${props.config.name} 审批人为表单中部门，但未指定`)
      return false
    }
    return true
  },
  ORGANIZATION_SELECT_COMPONENT: (err: string[]) => {
    if (props.config.props.formOrg === '') {
      state.errorInfo = '请指定表单中的组织控件'
      err.push(`${props.config.name} 审批人为表单中组织，但未指定`)
      return false
    }
    return true
  },
  REFUSE: () => {
    return true
  }
}

const handSelected = () => {
  emits('selected')
}
const handInsertNode = (type: string) => {
  emits('insertNode', type)
}
const handDelNode = () => {
  emits('delNode', props?.config)
}

defineExpose({ validate })
</script>

<template>
  <Node
    :title="config.name"
    :show-error="state.showError"
    :content="content"
    :error-info="state.errorInfo"
    placeholder="请设置审批人"
    header-bgc="#FF943E"
    header-icon="ikflow-shenhe"
    @selected="handSelected"
    @delNode="handDelNode"
    @insertNode="handInsertNode"
  />
</template>
